package com.example.newsapp.ui.components.pictureComponent

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.example.newsapp.data.compositionLocal.LocalNavControllerPicture
import com.example.newsapp.data.`object`.PictureNavigation
import com.example.newsapp.data.`object`.PictureState
import com.example.newsapp.ui.components.mainComponent.BottomNavtionSelected
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun TopTab(modifier: Modifier = Modifier) {
    val tabItems = listOf("推荐", "热门", "宠物", "风景", "建筑", "图画")
    var selected by rememberSaveable { mutableStateOf(0) }
    var navControllerPicture = LocalNavControllerPicture.current
    var scope = rememberCoroutineScope()

    ScrollableTabRow (
        selectedTabIndex = selected,
        modifier = Modifier.fillMaxWidth()
    ) {
        tabItems.forEachIndexed { index, title ->
            Tab(
                selected = selected == index,
                onClick = {
                    PictureState.previousTab = selected
                    selected = index
                    PictureState.currentTab = selected
                    PictureState.tabNum = selected
                    // 选择相同标签刷新界面
                    if(PictureState.previousTab == PictureState.currentTab) {
                        scope.launch {
                            PictureState.isRefresh = true
                            delay(2000)
                            PictureState.keyRefresh = true
                            PictureState.isRefresh = false
                        }
                    }
                    BottomNavtionSelected(
                        navController = navControllerPicture,
                        when (index) {
                            0 -> PictureNavigation.suggestList
                            1 -> PictureNavigation.hotList
                            2 -> PictureNavigation.petList
                            3 -> PictureNavigation.sceneList
                            4 -> PictureNavigation.building
                            5 -> PictureNavigation.drawList
                            else -> PictureNavigation.suggestList
                        }
                    )
                },
                selectedContentColor = Color(0xFFE1CE16),
                unselectedContentColor = Color.Black,
                text = { Text(text = title) }
            )
        }
    }
}